'use strict';

const BaseService = require('./base');
const dayjs = require('dayjs');

class OrderService extends BaseService {
  constructor(ctx) {
    super(ctx, 'Order');
  }

  // 生成订单编号
  generateOrderNo() {
    const timestamp = dayjs().format('YYYYMMDDHHmmss');
    const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
    return `O${timestamp}${random}`;
  }

  // 重写getPage方法，增加会员和订单项信息
  async getPage(where, page, pageSize) {
    const { app } = this.ctx;
    const include = [{
      model: app.model.Member,
      as: 'member',
      attributes: ['id', 'nickname', 'phone'],
    }, {
      model: app.model.OrderItem,
      as: 'items',
      include: [{
        model: app.model.Product,
        as: 'product',
      }],
    }];
    return super.getPage(where, page, pageSize, include);
  }

  // 创建订单
  async createOrder(orderData) {
    const { ctx, app } = this;
    const { items, ...orderInfo } = orderData;
    
    // 开启事务
    const transaction = await app.model.transaction();
    
    try {
      // 1. 检查商品是否存在且有库存
      for (const item of items) {
        const product = await app.model.Product.findByPk(item.productId);
        if (!product || product.status !== 1) {
          throw new Error(`商品 ${item.productId} 不存在或已下架`);
        }
        if (product.stock < item.quantity) {
          throw new Error(`商品 ${product.name} 库存不足`);
        }
      }

      // 2. 创建订单
      const order = await app.model.Order.create({
        ...orderInfo,
        orderNo: this.generateOrderNo(),
        status: 1, // 待支付
      }, { transaction });

      // 3. 创建订单项
      const orderItems = [];
      let totalAmount = 0;

      for (const item of items) {
        const product = await app.model.Product.findByPk(item.productId);
        const amount = product.price * item.quantity;
        
        const orderItem = await app.model.OrderItem.create({
          orderId: order.id,
          productId: item.productId,
          quantity: item.quantity,
          price: product.price,
          amount,
          productName: product.name,
          productImage: product.image,
        }, { transaction });

        orderItems.push(orderItem);
        totalAmount += amount;

        // 4. 更新商品库存
        await product.decrement('stock', { by: item.quantity, transaction });
      }

      // 5. 更新订单总金额
      await order.update({ totalAmount }, { transaction });

      // 提交事务
      await transaction.commit();

      return { ...order.toJSON(), items: orderItems };
    } catch (error) {
      // 回滚事务
      await transaction.rollback();
      throw error;
    }
  }

  // 取消订单
  async cancelOrder(id, memberId) {
    const { ctx, app } = this;
    
    // 开启事务
    const transaction = await app.model.transaction();
    
    try {
      const order = await app.model.Order.findOne({
        where: { id, memberId },
        include: [{
          model: app.model.OrderItem,
          as: 'items',
        }],
      });

      if (!order) {
        throw new Error('订单不存在');
      }

      if (order.status !== 1) {
        throw new Error('只能取消待支付的订单');
      }

      // 1. 更新订单状态
      await order.update({ status: 0 }, { transaction });

      // 2. 恢复商品库存
      for (const item of order.items) {
        await app.model.Product.increment('stock', {
          by: item.quantity,
          where: { id: item.productId },
          transaction,
        });
      }

      // 提交事务
      await transaction.commit();

      return order;
    } catch (error) {
      // 回滚事务
      await transaction.rollback();
      throw error;
    }
  }

  // 支付订单
  async payOrder(id, memberId, paymentMethod) {
    const order = await this.ctx.model.Order.findOne({
      where: { id, memberId },
    });

    if (!order) {
      throw new Error('订单不存在');
    }

    if (order.status !== 1) {
      throw new Error('订单状态错误');
    }

    await order.update({
      status: 2,
      paymentMethod,
      paymentTime: new Date(),
    });

    return order;
  }

  // 获取会员订单列表
  async getMemberOrders(memberId, status) {
    const { app } = this.ctx;
    const where = { memberId };
    if (status !== undefined) {
      where.status = status;
    }

    return await app.model.Order.findAll({
      where,
      include: [{
        model: app.model.OrderItem,
        as: 'items',
        include: [{
          model: app.model.Product,
          as: 'product',
        }],
      }],
      order: [['createdAt', 'DESC']],
    });
  }
}

module.exports = OrderService;
